package cn.iocoder.yudao.framework.datasource.provider;

import com.baomidou.dynamic.datasource.creator.DefaultDataSourceCreator;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DataSourceProperty;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.hikari.HikariCpConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * TODO
 *
 * @className: AbstractDataSourceProvider
 * @author: tangkh
 * @date: 2023-09-19 16:59
 */
public abstract class AbstractDataSourceProvider implements DynamicDataSourceProvider {
    private static final Logger log = LoggerFactory.getLogger(AbstractDataSourceProvider.class);
    @Autowired
    private DefaultDataSourceCreator defaultDataSourceCreator;

    public AbstractDataSourceProvider() {
    }

    public Map<String, DataSource> createDataSourceMap(Map<String, DataSourceProperty> dataSourcePropertiesMap) {
        Map<String, DataSource> dataSourceMap = new HashMap(dataSourcePropertiesMap.size() * 2);

        String dsName;
        DataSourceProperty dataSourceProperty;
        for(Iterator var3 = dataSourcePropertiesMap.entrySet().iterator(); var3.hasNext(); dataSourceMap.put(dsName, this.defaultDataSourceCreator.createDataSource(dataSourceProperty))) {
            Map.Entry<String, DataSourceProperty> item = (Map.Entry)var3.next();
            dsName = item.getKey();
            dataSourceProperty = item.getValue();
            String poolName = dataSourceProperty.getPoolName();
            if (poolName == null || poolName.isEmpty()) {
                poolName = dsName;
            }

            dataSourceProperty.setPoolName(poolName);
            HikariCpConfig hikari = dataSourceProperty.getHikari();
            if (hikari != null) {
                hikari.setMinIdle(2);
                hikari.setMaxPoolSize(200);
            }
        }

        return dataSourceMap;
    }
}
